<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '点单',
  },
}
</route>

<script setup lang="ts">
import { ref, watch, defineAsyncComponent } from 'vue'
import type { CartItems, GoodsDiscountVO } from '@/service/goods/coupon/coupon.d'
import { calculateBestDiscount } from '@/service/goods/coupon/coupon'
import { pageByCategory } from '@/service/goods/index'
import { GoodsSku, CategorySkuQuery } from '@/service/goods/goods.d'
import { getCartAllList } from '@/service/goods/cart/cart'
import type { GoodsCart } from '@/service/goods/cart/cart.d'
import { selectByParentId } from '@/service/goods/category/category'
import { GoodsCategory } from '@/service/goods/category/category.d'
import { debounce } from 'lodash-es'
import { useUserStore } from '@/store/user'
import { useActiveCartStore } from '@/store/activeCart'

const CartBar = defineAsyncComponent(() => import('@/components/cartBar/index.vue'))
const SelectdProduct = defineAsyncComponent(() => import('@/components/selectdProduct/index.vue'))
const SelectdProductRef = ref()
const userStore = useUserStore()
const activeCartStore = useActiveCartStore()

const modelValue = ref(true)

const getCategoryByParentID = async (parentId: number) => {
  try {
    const { code, data } = await selectByParentId(parentId)
    if (code === 200 && data && parentId === 0) {
      primaryList.value = data
    }
    if (code === 200 && data && parentId !== 0) {
      secondaryList.value = data
      switchSecondary(currentSecondaryIndex.value, secondaryList.value[0].id)
    }
  } catch (error) {
    uni.showToast({ title: '获取分类失败', icon: 'none' })
  }
}
const cartItemList = ref<GoodsCart[]>([])

const getCartAllListData = async () => {
  try {
    const { code, data } = await getCartAllList()
    if (code === 200 && data) {
      console.log(data)

      cartItemList.value = data
      activeCartStore.setCart(data)
    } else {
      throw new Error('获取购物车数据失败')
    }
  } catch (error) {
    uni.showToast({ title: '获取购物车数据失败', icon: 'none' })
  }
}
getCartAllListData()

const showModlePop = (skuId: number | string, goodsId: number | string) => {
  modelValue.value = false
  SelectdProductRef.value.hanleOpen(skuId, goodsId)
  console.log(skuId, goodsId)
}
const calculateDiscount = (salePrice: number, marketPrice: number) => {
  if (marketPrice === 0 || salePrice === marketPrice) return ''
  return ((salePrice / marketPrice) * 10).toFixed(1)
}

const goSkuInfo = (skuId: number, goodsId: number) => {
  uni.navigateTo({ url: `/pages/goods/info-index?id=${goodsId}&skuId=${skuId}` })
}

// 滚动位置控制
const primaryScrollLeft = ref(0)
const secondaryScrollTop = ref(0)
// 分页控制
const query = ref<CategorySkuQuery>({
  current: 1,
  size: 10,
  categoryId: null,
})

// 当前选中索引
const currentPrimaryIndex = ref(0) // 一级分类索引

const currentSecondaryIndex = ref(0) // 二级分类索引
onLoad(async (options) => {
  await getCategoryByParentID(0)
  console.log(options)
  // 等待数据加载完成后再处理参数
  if (options?.id != null && Number(options.id) >= 0) {
    const targetIndex = primaryList.value.findIndex((item) => item.id === options.id)
    console.log(primaryList.value)

    console.log('targetIndex', targetIndex)

    if (targetIndex !== -1) {
      currentPrimaryIndex.value = targetIndex
      switchPrimary(targetIndex) // 主动触发分类切换
    }
  }
})
// 一级分类数据
const primaryList = ref<GoodsCategory[]>([])

const loadMore = () => {
  if (loadStatus.value === 'noMore') {
    const nextIndex = currentSecondaryIndex.value + 1
    const id = secondaryList.value[nextIndex].id

    if (nextIndex < secondaryList.value.length) {
      switchSecondary(nextIndex, id)
    }
    return
  }
  loadGoods()
}
// 二级分类数据
const getSecondaryList = (primaryId: number) => {
  getCategoryByParentID(primaryId)
}
watch(
  [primaryList, currentPrimaryIndex],
  ([newList, newIndex]) => {
    if (newList.length > 0 && newIndex < newList.length) {
      getSecondaryList(newList[newIndex].id)
      currentSecondaryGoodsId.value = newList[newIndex].id // 同步更新商品分类ID
    }
  },
  { immediate: true },
)

// 二级分类计算属性
const secondaryList = ref<GoodsCategory[]>([])

// 商品数据
const currentGoods = ref<GoodsSku[]>([])
const loadStatus = ref<'more' | 'loading' | 'noMore'>('more')

// 切换一级分类
const switchPrimary = (index: number) => {
  currentPrimaryIndex.value = index
  currentSecondaryIndex.value = 0
  currentGoods.value = []
  getSecondaryList(primaryList.value[index].id)
  loadGoods(true)
}
const currentSecondaryGoodsId = ref(null)
// 切换二级分类
const switchSecondary = (index: number, id: number) => {
  currentSecondaryIndex.value = index
  currentSecondaryGoodsId.value = id
  currentSecondaryGoodsId.value = loadGoods(true)
}

// 根据分类id获取商品数据
const mockGoods = async (count: number) => {
  query.value.categoryId = count
  try {
    const { code, data } = await pageByCategory(query.value)
    if (code === 200 && data)
      currentGoods.value = data.records.map((item) => {
        item.calculateDiscount = calculateDiscount(item.salePrice, item.marketPrice)
        return item
      })
  } catch (error) {
    uni.showToast({ title: '获取商品失败', icon: 'none' })
  }
}

// 加载商品
const loadGoods = async (reset = false) => {
  loadStatus.value = 'loading'

  if (reset) {
    query.value.current = 1
    mockGoods(currentSecondaryGoodsId.value)
  } else {
    mockGoods(currentSecondaryGoodsId.value)
  }

  query.value.current++
  // loadStatus.value = currentPage.value < 3 ? 'more' : 'noMore'
}

const discountList = ref<GoodsDiscountVO[]>([])
watch(
  () => cartItemList.value,
  debounce((newVal) => {
    if (newVal.length > 0) {
      console.log('带防抖的监听器（500ms防抖间隔）', newVal)
      discountList.value = []
      const items = []
      newVal?.forEach((item) => {
        if (item.selected === 1) {
          const obj: CartItems = {
            skuId: item.skuId,
            quantity: item.goodsNum,
          }
          items.push(obj)
        }
      })
      calculateBestDiscount({
        userId: Number(userStore.userInfo.id),
        cartItems: items,
      }).then((res) => {
        console.log(res)
        if (res.code === 200 && res.data.length > 0) {
          discountList.value = res.data
          console.log(discountList)
        }
      })
    }
  }, 100),
  { deep: true },
)
const onPopClose = () => {
  modelValue.value = true
}
// 初始化加载
loadGoods(true)
</script>
<template>
  <view class="category-page">
    <!-- 一级分类横向滚动 -->
    <view class="primary-scroll-box">
      <scroll-view
        class="primary-scroll"
        scroll-x
        :scroll-left="primaryScrollLeft"
        scroll-with-animation
      >
        <view
          v-for="(item, index) in primaryList"
          :key="item.id"
          class="primary-item"
          :class="{ active: currentPrimaryIndex === index }"
          @click="switchPrimary(index)"
        >
          <view class="primary-img"><image-container :src="item.imageUrl"></image-container></view>
          <text
            class="primary-name"
            :class="{ 'active-primary-name': currentPrimaryIndex === index }"
          >
            {{ item.name }}
          </text>
        </view>
      </scroll-view>
    </view>

    <!-- 二级分类+商品列表 -->
    <view class="container">
      <!-- 左侧二级分类 -->
      <view style="width: 180rpx">
        <scroll-view class="secondary-scroll" scroll-y :scroll-top="secondaryScrollTop">
          <view
            v-for="(item, index) in secondaryList"
            :key="item.id"
            class="secondary-item"
            :class="{ active: currentSecondaryIndex === index }"
            @click="switchSecondary(index, item.id)"
          >
            {{ item.name }}
          </view>
        </scroll-view>
      </view>

      <!-- 右侧商品列表 -->
      <scroll-view class="goods-scroll" scroll-y @scrolltolower="loadMore">
        <view class="goods-list">
          <view v-for="(goods, index) in currentGoods" :key="index" class="goods-item">
            <image
              class="goods-img"
              :src="goods.thumbImg"
              @click.stop="goSkuInfo(goods.id, goods.goodsId)"
            />
            <view class="goods-info">
              <text class="goods-title" @click.stop="goSkuInfo(goods.id, goods.goodsId)">
                {{ goods.skuName }}
              </text>
              <text class="goods-sales" v-if="goods.calculateDiscount != ''">
                {{ goods.calculateDiscount }}折
              </text>
              <view class="price-box">
                <text class="price">{{ goods.salePrice }}</text>
                <!-- <uni-number-box :min="0" :value="0" @change="changeCount(goods, $event)" /> -->
                <view @click.stop="showModlePop(goods.id, goods.goodsId)">
                  <view class="changeButtom">选规格</view>
                </view>
              </view>
            </view>
          </view>
          <uni-load-more :status="loadStatus" />
        </view>
      </scroll-view>
    </view>
    <SelectdProduct model-type="buy" ref="SelectdProductRef" @popClose="onPopClose" />
    <!-- <CartBar
      model-type="categorize"
      :discount-list="discountList"
      :cart-list="cartItemList"
      :model-value="modelValue"
      bottom="0"
    /> -->
  </view>
</template>
<style lang="scss" scoped>
/* 保持原有样式不变 */
.category-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 88rpx);
  .primary-scroll-box {
    position: relative;
    display: flex;
    height: 160rpx;
    .primary-scroll {
      width: 680rpx;
      padding-top: 20rpx;
      white-space: nowrap;
      background: linear-gradient(180deg, $uni-bg-themes-abate 0%, #fff9eb 100%);
      .primary-item {
        display: inline-flex;
        flex-direction: column;
        align-items: center;
        width: 100rpx;
        padding: 10rpx;
        // opacity: 0.6;
        .primary-name {
          padding: 2rpx 10rpx;
          font-size: 20rpx;
          color: #666;
        }
        .active-primary-name {
          font-weight: normal;
          color: #333;
          background: #fff;
          border-radius: 12rpx;
        }
        &.active {
          // opacity: 1;
          .primary-name {
            font-weight: bold;
            color: #ff5f15;
          }
        }

        .primary-img {
          width: 60rpx;
          height: 70rpx;
          margin-bottom: 10rpx;
        }
      }
    }
    .primary-scroll-right {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 70rpx;
      .vertical-text {
        font-size: 24rpx;
        color: #333;
        text-align: center;
        writing-mode: vertical-rl;
        text-orientation: upright;
      }
      .tabbar-gengduo {
        margin-top: 10rpx;
        font-size: 48rpx;
      }
    }
    // .primary-bar {
    //   position: absolute;
    //   bottom: 100rpx;
    //   left: 0;
    //   width: 750rpx;
    //   min-height: 400rpx;
    //   background-color: #fff;
    // }
  }

  .container {
    display: flex;
    justify-content: space-between;
    height: calc(100vh - 250rpx);
    // padding-top: 30rpx;
    overflow: hidden;
    background: #fff;
    border-radius: 16rpx;

    .secondary-scroll {
      width: 180rpx;
      background: #fff;
      .secondary-item {
        padding: 30rpx 20rpx;
        font-size: 26rpx;
        color: #666;
        text-align: center;
        background: #fff;

        &.active {
          position: relative;
          font-weight: bold;
          color: #ff5f15;
          background: #fff;

          &::after {
            position: absolute;
            top: 50%;
            left: 0;
            width: 6rpx;
            height: 40rpx;
            content: '';
            background: #ff5f15;
            transform: translateY(-50%);
          }
        }
      }
    }

    .goods-scroll {
      flex: 1;
      padding: 20rpx;
      background-color: #f5f5f5;
      .goods-list {
        padding-bottom: 30rpx;
      }
      .goods-item {
        display: flex;
        padding: 20rpx;
        padding-bottom: 30rpx;
        margin-bottom: 20rpx;
        background: #fff;
        border-radius: 16rpx;

        .goods-img {
          width: 140rpx;
          height: 140rpx;
          margin-right: 20rpx;
          border: 2rpx solid #f5f5f5;
          border-radius: 8rpx;
        }

        .goods-info {
          display: flex;
          flex: 1;
          flex-direction: column;
          justify-content: space-between;
          width: 330rpx;

          .goods-title {
            display: -webkit-box;
            overflow: hidden;
            font-size: 24rpx;
            color: #333;
            text-overflow: ellipsis;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          .goods-sales {
            width: 44rpx;
            padding: 0 2rpx;
            font-size: 18rpx;
            line-height: 1.4;
            color: $uni-bg-themes;
            text-align: center;
            border: 1rpx solid $uni-bg-themes;
            border-radius: 6rpx;
          }

          .price-box {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .price {
              font-size: 32rpx;
              font-weight: bold;
              color: #ff5f15;
              &::before {
                font-size: 22rpx;
                content: '￥';
              }
            }
            .changeButtom {
              width: 66rpx;
              padding: 8rpx 6rpx;
              font-size: 20rpx;
              line-height: 1 !important;
              color: white;
              text-align: center;
              background-color: #e5492a;
              border-radius: 6rpx;
            }
          }
        }
      }
    }
  }
}
</style>
